#include <QMenu>
#include <QToolButton>

#include <private/menu/cxitoplevelmenu/cxitoplevelmenu_p.h>

CxiTopLevelMenuPrivate::CxiTopLevelMenuPrivate(CxiTopLevelMenu* q)
	: q_ptr(q),
	  m_hLayout(new QHBoxLayout(q)),
	  m_flowBtn(new QToolButton(q)),
	  m_menu(new QMenu(q)),
	  m_actionGroup(new QActionGroup(q))
{
	init();
}

CxiTopLevelMenuPrivate::~CxiTopLevelMenuPrivate() = default;


void CxiTopLevelMenuPrivate::init()
{
	Q_Q(CxiTopLevelMenu);

	m_hLayout->setContentsMargins(0, 0, 0, 0);
	m_hLayout->setSpacing(0);

	m_hLayout->setAlignment(Qt::AlignLeft);
	m_hLayout->addWidget(m_flowBtn);
	q->setLayout(m_hLayout);

	m_flowBtn->setMenu(m_menu);
	m_flowBtn->setPopupMode(QToolButton::InstantPopup);
	m_flowBtn->setVisible(false);

}

void CxiTopLevelMenuPrivate::updateLayout()
{
	Q_Q(CxiTopLevelMenu);
	int spaceWidth = m_hLayout->spacing();
	int avialiableWidth = q->width() - m_flowBtn->width() - spaceWidth;
	int usedWidth = 0;
	m_menu->clear();
	for (int i = 0 ;i < m_hLayout->count() - 1;++ i)
	{
		auto item = m_hLayout->itemAt(i);
		auto* toolBtn = qobject_cast<QToolButton*>(item->widget());
		if (toolBtn)
		{
			auto itemWidth = toolBtn->width()  + spaceWidth;
			if (usedWidth + itemWidth < avialiableWidth)
			{
				m_flowBtn->setVisible(false);
				usedWidth += itemWidth;
				toolBtn->setVisible(true);
			}
			else
			{
				m_flowBtn->setVisible(true);
				toolBtn->setVisible(false);
				m_menu->addAction(toolBtn->defaultAction());
			}
		}
	}

}